<script setup>
import { User, Lock } from '@element-plus/icons-vue';
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { userRegisterService, userLoginService, userInfoService, getTeacherInfoService } from '@/api/user.js';
import { useTokenStore } from '@/stores/token.js';
import useUserInfoStore from '@/stores/userInfo.js';
import { useRouter } from 'vue-router';

const isRegister = ref(false);

const registerData = ref({
  username: '',
  password: '',
  rePassword: '',
  type: '学生'
});

const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次确认密码'));
  } else if (value !== registerData.value.password) {
    callback(new Error('请确保两次输入的密码一样'));
  } else {
    callback();
  }
};

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
  ],
  rePassword: [
    { validator: checkRePassword, trigger: 'blur' }
  ]
};

const router = useRouter();

const register = async () => {
  try {
    let result = await userRegisterService(registerData.value);
    if (result.code === 0) {
      ElMessage.success(result.msg ? result.msg : '注册成功');
      // 登录注册成功后的账号
      await loginAfterRegister();
    } else {
      ElMessage.error(result.msg ? result.msg : '注册失败');
    }
  } catch (error) {
    ElMessage.error('注册失败，请重试');
  }
};

const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();

const getTeacherInfo = async () => {
  try {
    const userInfoResult = await userInfoService();
    if (userInfoResult.code === 0) {
      userInfoStore.setInfo(userInfoResult.data);
      if (userInfoResult.data.type === '教师') {
        const teacherInfoResult = await getTeacherInfoService();
        if (!teacherInfoResult.data) {
          router.push('/teacher/improve');
          ElMessage.error('请完善信息');
        } else {
          userInfoStore.setTeacherInfo(teacherInfoResult.data);
        }
      }
    } else {
      ElMessage.error(userInfoResult.msg || '获取用户信息失败');
    }
  } catch (error) {
//不需要提示，因为信息完整
  }
};

const login = async () => {
  try {
    let result = await userLoginService(registerData.value);
    if (result.code === 0) {
      ElMessage.success(result.msg ? result.msg : '登录成功');
      tokenStore.setToken(result.data);
      getTeacherInfo();
      router.push('/');
    } else {
      ElMessage.error(result.msg ? result.msg : '登录失败');
    }
  } catch (error) {
    ElMessage.error('登录失败，请重试');
  }
};

const loginAfterRegister = async () => {
  try {
    // 使用注册后的账号进行登录
    await login();
    // 登录成功后根据用户类型跳转到相应页面
    if (registerData.value.type === '学生') {
      router.push('/student/improve');
    } else if (registerData.value.type === '家长') {
      router.push('/patriarch/improve');
    }
  } catch (error) {
    ElMessage.error('登录失败，请重试');
  }
};

const clearRegisterData = () => {
  registerData.value = {
    username: '',
    password: '',
    rePassword: '',
    type: '学生'
  };
};

const userTypes = ['学生', '家长', '教师', '领导', '管理员'];
</script>


<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-if="isRegister" :model="registerData" :rules="rules">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item prop="rePassword">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.rePassword"></el-input>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-radio-group v-model="registerData.type">
            <el-radio v-for="type in userTypes.slice(0, 2)" :key="type" :label="type">{{ type }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="register">注册</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false; clearRegisterData()">← 返回</el-link>
        </el-form-item>
      </el-form>

      <!-- 登录表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-else :model="registerData" :rules="rules">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.password"></el-input>
        </el-form-item>
        <el-form-item label="用户类型">
          <el-select v-model="registerData.type" placeholder="请选择用户类型">
            <el-option v-for="type in userTypes" :key="type" :label="type" :value="type"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true; clearRegisterData()">注册 →</el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: url('@/assets/login_title.png') no-repeat 60% calc(50% - 240px) / 400px auto,
    url('@/assets/login_bg.jpg') no-repeat center / 100% auto;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
